package com.t1.demo.Share;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipInputStream;

/**
 * @Description:学员端实时接收数据 显示窗口用Swing展示
 * @Author: 杨淮尊
 * @Date: 2020/4/13
 **/
public class Socket_Client extends Thread {
    //Swing相关
    public BorderInit frame;
    //Socket
    public Socket socket;
    //Socket Server Port
    public Integer SERVERPORT;
    //IP
    public static String IP;

    //构造 参数为Swing设置和IP
    public Socket_Client(BorderInit frame,String IP,Integer SERVERPORT)
    {
        this.SERVERPORT=SERVERPORT;
        this.frame = frame;
        this.IP=IP;
    }

    public void run() {
        while(frame.getFlag()){
            try {
                //建立连接
                socket = new Socket(IP,SERVERPORT);
                //获取桌面实时图片
                DataInputStream ImgInput = new DataInputStream(socket.getInputStream());
                ZipInputStream imgZip = new ZipInputStream(ImgInput);
                imgZip.getNextEntry();             //到Zip文件流的开始处
                Image img = ImageIO.read(imgZip);  //按照字节读取Zip图片流里面的图片
                //设置图片
                frame.jlbImg.setIcon(new ImageIcon(img));
                //校验组件
                frame.validate();
                //延时
                TimeUnit.MILLISECONDS.sleep(50);// 接收图片间隔时间
                //关流
                imgZip.close();
            } catch (InterruptedException | IOException e) {
                System.out.println("出现异常连接断开");
            }finally{
                try {
                    //Socket关流
                    socket.close();
                } catch (IOException e) {}
            }
        }
    }
}